package wafteam.others;

import java.util.ArrayList;

import wafteam.comicview.R;
import wafteam.database.Chap;
import wafteam.database.Database;
import android.app.Activity;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class ComicArrayAdapter extends ArrayAdapter<Chap>{
	Activity context = null;
	ArrayList<Chap> arr = null;
	int layoutId;
	
	// Constructor
	public ComicArrayAdapter(Activity context, int id, ArrayList<Chap> array){
		super(context, id, array);
		this.arr = array;
		this.context = context;
		this.layoutId = id;
	}
	
	// Custom layout
	public View getView(int pos, View convertView, ViewGroup parent){
		LayoutInflater inflater = context.getLayoutInflater();
		convertView = inflater.inflate(layoutId, null);
		// Use for AsyncTask
		final View view = convertView;
		
		// Get chapter at position pos
		final Chap chapter = arr.get(pos);
		final int chapId = pos;
		
		// Find control views in item listview
		ImageView chapImg = (ImageView) convertView.findViewById(R.id.chap_img);
		TextView chapName = (TextView) convertView.findViewById(R.id.chap_name);
		TextView size = (TextView) convertView.findViewById(R.id.size);
		ImageView download = (ImageView) convertView.findViewById(R.id.download);
		final ViewFlipper switcher = (ViewFlipper) convertView.findViewById(R.id.download_switch);
		if (chapter.getIsDownload()==1){
			switcher.showPrevious();
		}
		
		// Set value for this control views
		// Chapter's image
		String uriIco = "drawable/tap1";
		int ImgSrc = convertView.getContext().getResources().getIdentifier(uriIco, null,
				convertView.getContext().getApplicationContext().getPackageName()); 
		chapImg.setImageResource(ImgSrc);
		// Chapter's name
		chapName.setText(chapter.getChapName());
		// Size of chapter
		size.setText(String.valueOf(chapter.getSize())+" MB");
		// Download all images of a chapter to read offline
		download.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switcher.showNext();
				
				DownloadFromURL down = new DownloadFromURL(view);
				if (chapId <10){
					down.execute("http://cse.hcmut.edu.vn/~hiep/SlideOOP/LyThuyetOOP_New/Chuong0"+chapId+".pdf");
				}
				Database db = new Database(context);
				chapter.setIsDownload(1);
				db.updateChap(chapter);
				db.close();
				
			}
		});
		
		return convertView;
	}
}
